/*
 * Copyright (C) 2008  Wang Hoi <fearee@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  US
*/
#include "connection.h"
#include "server.h"
#include "settings.h"
Connection::Connection(QTcpSocket *s, Server *sr): srv(sr), socket(s), srcBuffer(0)
{
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), SIGNAL(error(QAbstractSocket::SocketError)));
    connect(socket, SIGNAL(disconnected()), SIGNAL(disconnected()));
    connect(socket, SIGNAL(readyRead()), SLOT(onReadyRead()));
    connect(socket, SIGNAL(bytesWritten(qint64)), SLOT(onBytesWritten(qint64)));
}
Connection::~Connection()
{
    socket->deleteLater();
}
QAbstractSocket::SocketError Connection::error() const
{
    return socket->error();
}
void Connection::disconnectFromHost()
{
    socket->disconnectFromHost();
}
void Connection::onReadyRead()
{
    QRegExp req("GET /(.*) HTTP");
    QRegExp uri("([^\\?]*)(\\?time=(-?\\d+))? *$");
    QByteArray buf;

    buf = socket->readAll();
    if (req.indexIn(buf) != -1) {
        if (uri.indexIn(req.cap(1)) != -1) {
            reqURI = uri.cap(1);
            if (uri.cap(3).size()) {
                reqTime = uri.cap(3).toLongLong();
            } else {
                reqTime = 0x7FFFFFFF;
            }
            srcBuffer = srv->getBuffer(reqURI);
            if (srcBuffer) {
                connect(srcBuffer, SIGNAL(dataReady(quint64, const QByteArray &)),
                        SLOT(onDataGot(quint64, const QByteArray &)));
                connect(srcBuffer, SIGNAL(underBuffer(quint64)),
                        SLOT(onUnderBuffer(quint64)));
                currentPos = srcBuffer->timeToPos(reqTime);
                if (currentPos<0) {
                    socket->disconnectFromHost();
                    return;
                }
                buf.clear();
                buf.append("HTTP/1.0 200 OK\r\n");
                buf.append("Content-type: application/octet-stream\r\n");
                buf.append("Cache-Control: no-cache\r\n\r\n");
                socket->write(buf);
            } else {
                qWarning() << "can't get " << reqURI;
                socket->disconnectFromHost();
            }
        }
    }
}
void Connection::onBytesWritten(qint64 writedLen)
{
    QByteArray buf;

    // qDebug() << "onBytesWritten" << writedLen;
    if (srcBuffer && (socket->bytesToWrite() == 0)) {
        srcBuffer->getData(currentPos);
    }
}
void Connection::onDataGot(quint64 pos, const QByteArray &buf)
{
    QByteArray nbuf;
    // qDebug() << "Connection::onDataGot:" << currentPos << pos << buf.size();
    if ((currentPos >= pos) && (currentPos < pos + buf.size())) {
        nbuf = buf.mid(currentPos - pos);
        currentPos += nbuf.size();
	if (socket->bytesToWrite()<(srv->setting()->chunkSize())) {
	    srcBuffer->getData(currentPos);
        }
        socket->write(nbuf);
    }
}
void Connection::onUnderBuffer(quint64 pos)
{
    if (currentPos < pos) {
        qWarning() << "Connection underbuffer!" << currentPos << pos;
        socket->disconnectFromHost();
    }
}

#include "connection.moc"
